import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL, // 接口基础地址（从环境变量读取）
    timeout: 5000
})

// 请求拦截器：添加令牌
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('access_token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器：处理错误和令牌过期
service.interceptors.response.use(
    (response) => {
        // 只返回data部分
        return response.data
    },
    async (error) => {
        const originalRequest = error.config

        // 处理401未授权（令牌过期）
        if (error.response?.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true // 避免重复刷新令牌
            try {
                // 尝试刷新令牌
                const refreshToken = localStorage.getItem('refresh_token')
                if (refreshToken) {
                    const res = await axios.post(
                        `${import.meta.env.VITE_API_BASE_URL}/auth/refresh`,
                        { refresh_token: refreshToken }
                    )
                    // 刷新成功：更新令牌
                    localStorage.setItem('access_token', res.data.data.access_token)
                    // 重新发送原请求
                    originalRequest.headers.Authorization = `Bearer ${res.data.data.access_token}`
                    return service(originalRequest)
                }
            } catch (refreshError) {
                // 刷新令牌失败：清除令牌并跳登录页
                localStorage.removeItem('access_token')
                localStorage.removeItem('refresh_token')
                router.push('/auth/login')
            }
        }

        // 全局错误提示
        ElMessage.error(error.response?.data?.message || '操作失败')
        return Promise.reject(error)
    }
)

export default service